package com.arcbees.test.collaborative.client;

import com.arcbees.test.collaborative.client.diffsync.ClientDocumentShadowImpl;
import com.arcbees.test.collaborative.server.diffsync.ServerDiffMatchPatch;
import com.arcbees.test.collaborative.shared.diffsync.DiffHandler;
import com.arcbees.test.collaborative.shared.diffsync.DocumentShadow;
import com.arcbees.test.collaborative.shared.diffsync.Edits;
import com.arcbees.test.collaborative.shared.diffsync.PatchResult;

public class FakeClient {

  private FakeServer server;
  private DocumentShadow documentShadow;
  private DiffHandler diffHandler;
  private String clientText;

  // For debug only
  public int clientID;

  public FakeClient(FakeServer server, int clientID) {
    this.server = server;
    this.clientID = clientID;
    clientText = "";
    this.diffHandler = new DiffHandler(new ServerDiffMatchPatch());
    documentShadow = new ClientDocumentShadowImpl(diffHandler);
    server.subscribe(this);
  }

  public void receiveEdits(Edits edits) {
    if (edits.hasEdits()) {
      documentShadow.applyEdits(edits);
      PatchResult result = diffHandler.applyEdits(edits, clientText);
      clientText = result.getNewText();
    }
  }

  public void updateText(String newText) {
    clientText = newText;
    Edits edits = diffHandler.getEdits(documentShadow, newText);
    if (edits.hasEdits()) {
      documentShadow.updateText(newText);
    }
    server.receiveEdits(this, edits);
  }

  public String getText() {
    return clientText;
  }
}
